package com.lifengdi.qiankun.lucene;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.SearcherManager;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Objects;

/**
 * @author: 李锋镝
 * @date: 2020-06-30 10:28
 */
@Configuration
public class LuceneConfig {

    @Value("${lucene.indexDir:#{null}}")
    private String indexDir;

    @Bean
    public Analyzer analyzer() {
        return new IKAnalyzer(false);
    }
    /**
     * 索引位置
     * @return Directory
     */
    @Bean
    public Directory directory() throws IOException {
        Objects.requireNonNull(indexDir, "Lucene索引目录不能为空");
        if (indexDir.trim().equals("")) {
            throw new NullPointerException("Lucene索引目录不能为空");
        }
        File dir = new File(indexDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return FSDirectory.open(Paths.get(indexDir));
    }

    /**
     * 创建 IndexReader
     * @param directory 索引位置
     * @return IndexReader
     * @throws IOException IOException
     */
    @Bean
    public IndexReader indexReader(Directory directory, Analyzer analyzer) throws IOException {
        IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer);
        IndexWriter indexWriter = new IndexWriter(directory, indexWriterConfig);
        indexWriter.commit();
        indexWriter.close();
        return DirectoryReader.open(directory);
    }

    /**
     * 创建 SearcherManager
     * @param directory 索引位置
     * @return SearcherManager
     * @throws IOException IOException
     */
    @Bean
    public SearcherManager searcherManager(Directory directory, Analyzer analyzer) throws IOException {
        IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer);
        IndexWriter indexWriter = new IndexWriter(directory, indexWriterConfig);
        indexWriter.commit();
        indexWriter.close();
        return new SearcherManager(directory, null);
    }

    /**
     * 创建 IndexSearcher
     * @param indexReader IndexReader
     * @return IndexSearcher
     */
    @Bean
    public IndexSearcher indexSearcher(IndexReader indexReader){
        return new IndexSearcher(indexReader);
    }
}
